import { existsSync, readFileSync, writeFileSync } from 'fs';
import { join } from 'path';
import Vue from 'vue/dist/vue';
import { convertDBToPath, createFolderByDB, getTemplate } from '../../utils';

function getPackageJson(name: string, desc: string, engine: string, version: string) {
    return `{
    "name": "${name}",
    "version": "${version}",
    "engine": ">=${engine}",
    "description": "${desc}",
    "main": "index.ts",
    "scripts": {
        "test": "echo \\"Error: no test specified\\" && exit 1"
    },
    "repository": {
        "type": "git",
        "url": "https://gitee.com/cocos2d-zp/cococs-creator-frame-3d"
    },
    "publishConfig": {
        "access": "public",
        "registry": "https://registry.npmjs.org"
    },
    "license": "MIT"
}`;
}

function getIndexTs() {
    return `// 负责导出assets下的模块，如: export { default } from './assets/xxx.ts'
export default {};
`;
}

function getNpmignore() {
    return `#/////////////////////////////////////////////////////////////////////////////
# files
#/////////////////////////////////////////////////////////////////////////////
test
test.meta
node_modules
node_modules.meta
`;
}

function getReadme(name: string, desc: string) {
    return `# ${desc || name}

## 前置条件
[游戏引擎](https://www.cocos.com/en/creator-download)
[开发框架](https://github.com/a1076559139/cocos-creator-frame-3d)

## 使用案例
\`\`\`TS
import {} from 'db://pkg/${name}';

...
\`\`\`
`;
}

function getTestRD(name: string) {
    let result = '';
    for (let index = 0, up = false; index < name.length; index++) {
        const char = name[index];
        if (char === '-') {
            up = true;
        } else if (up || index == 0) {
            up = false;
            result += char.toLocaleUpperCase();
        } else {
            result += char;
        }
    }

    return `存放测试用例(包括脚本、场景、预制体等)，例如：
${result}Test.ts
${result}Test.scene`;
}

export default Vue.extend({
    template: getTemplate('pkg-create'),
    data() {
        return {
            display: '',
            showLoading: false,

            inputName: '',
            inputDesc: ''
        };
    },
    methods: {
        async onClickCreate() {
            this.display = '创建中';
            this.showLoading = true;

            if (new RegExp('^(?:(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)?/[a-z0-9-._~])|[a-z0-9-~])[a-z0-9-._~]*$').test(this.inputName) === false) {
                this.showLoading = false;
                this.display = '[错误] 名字不合法, 匹配规则: ^(?:(?:@(?:[a-z0-9-*~][a-z0-9-*._~]*)?/[a-z0-9-._~])|[a-z0-9-~])[a-z0-9-._~]*$';
                return;
            }

            const name = this.inputName.split('/').pop();
            const rootPath = `db://assets/${name}`;

            // 项目目录
            if (!await createFolderByDB(rootPath, {
                subFolders: [
                    {
                        folder: 'assets'
                    },
                    {
                        folder: 'test',
                        readme: getTestRD(name)
                    }
                ]
            })) {
                this.showLoading = false;
                this.display = '[错误] 创建失败';
                return;
            }

            let engine = '3.6.0';
            const projectJsonPath = join(__dirname, '../../../../../../package.json');
            if (existsSync(projectJsonPath)) {
                try {
                    const projectJsonStr = readFileSync(projectJsonPath);
                    const projectJson = JSON.parse(projectJsonStr);
                    engine = projectJson?.version || projectJson?.creator?.version || '3.6.0';
                } catch (error) { 1; }
            }

            let version = '1.0.0';
            const packageJsonPath = join(convertDBToPath(rootPath), 'package.json');
            if (existsSync(packageJsonPath)) {
                try {
                    const packageJsonStr = readFileSync(packageJsonPath);
                    const packageJson = JSON.parse(packageJsonStr);
                    version = packageJson?.version || '1.0.0';
                } catch (error) { 1; }
            }

            writeFileSync(packageJsonPath, getPackageJson(
                this.inputName,
                this.inputDesc,
                engine,
                version
            ), { encoding: 'utf-8' });

            const indexTsPath = join(convertDBToPath(rootPath), 'index.ts');
            writeFileSync(indexTsPath, getIndexTs(), { encoding: 'utf-8' });

            const npmignorePath = join(convertDBToPath(rootPath), '.npmignore');
            writeFileSync(npmignorePath, getNpmignore(), { encoding: 'utf-8' });

            const readmePath = join(convertDBToPath(rootPath), `.${name}.md`);
            writeFileSync(readmePath, getReadme(this.inputName, this.inputDesc), { encoding: 'utf-8' });

            this.showLoading = false;
            this.display = `[成功] 创建成功\n${rootPath}\n`;
        }
    },
});